package com.bcx.wind.workflow.core.flow.check;

import com.bcx.wind.workflow.core.flow.Model;
import com.bcx.wind.workflow.support.ObjectHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用来校验流程中重复名称节点
 * 缓存已经创建的节点对象，可以在递归中直接使用，提高性能
 * </p>
 *
 * @author zhanglei
 * @since 2019-03-12
 */
public class NodeCache {

    private NodeCache(){}

    private  ThreadLocal<Map<String,Model>> allNodes = new ThreadLocal<>();

    private static class NodeCacheInstance{
        private NodeCacheInstance(){}
        private static NodeCache cache = new NodeCache();
    }

    public static NodeCache getInstance(){
        return NodeCacheInstance.cache;
    }

    public void put(String nodeName , Model model){
        if(ObjectHelper.isEmpty(allNodes.get())){
            Map<String,Model> nodeModelMap = new HashMap<>(8);
            nodeModelMap.put(nodeName,model);
            allNodes.set(nodeModelMap);
            return;
        }

        allNodes.get().put(nodeName,model);
    }


    public void remove(){
        this.allNodes.remove();
    }

    public Model get(String nodeName){
        if(ObjectHelper.isEmpty(allNodes.get())){
            return null;
        }
        return allNodes.get().get(nodeName);
    }

    public void remove(String nodeName){
        if(!ObjectHelper.isEmpty(allNodes.get())){
            allNodes.get().remove(nodeName);
        }
    }

    public boolean contain(String nodeName){
        return !ObjectHelper.isEmpty(allNodes.get()) && allNodes.get().containsKey(nodeName);
    }

    public Map<String,Model>  get(){
        return this.allNodes.get();
    }

}